package com.tonghe.controller;

import com.tonghe.domain.ResponseResult;
import com.tonghe.domain.entity.LoginUser;
import com.tonghe.domain.entity.Menu;
import com.tonghe.domain.entity.User;
import com.tonghe.enums.AppHttpCodeEnum;
import com.tonghe.exception.SystemException;
import com.tonghe.service.LoginService;
import com.tonghe.service.MenuService;
import com.tonghe.service.RoleService;
import com.tonghe.utils.BeanCopyUtils;
import com.tonghe.utils.SecurityUtils;
import com.tonghe.vo.UserInfoVo;
import com.tonghe.vo.sys.AdminUserInfoVo;
import com.tonghe.vo.sys.RoutersVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @Date:2022/9/3- 09- 03- 15:44
 * @author: tonghe
 **/
@RestController
public class LoginController {

    @Autowired
    private LoginService loginService;

    @Autowired
    private MenuService menuService;

    @Autowired
    private RoleService roleService;

    /** 用户登录后台系统 */
    @PostMapping("/user/login")
    public ResponseResult login(@RequestBody User user){

        if(!StringUtils.hasText(user.getUserName())){
            throw new SystemException(AppHttpCodeEnum.REQUIRE_USERNAME);
        }
        return loginService.login(user);
    }

    /** 用户退出登录后台系统 */
    @PostMapping("/user/logout")
    public ResponseResult logout(){
        return loginService.logout();
    }

    /** 获取用户基本信息 */
    @GetMapping("/getInfo")
    public ResponseResult<AdminUserInfoVo> getInfo(){

        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long id = loginUser.getUser().getId();

        List<String> perms = menuService.selectPermsByUserId(id);
        List<String> roleKeyList = roleService.selectRoleKeyByUserId(id);

        AdminUserInfoVo adminUserInfoVo = new AdminUserInfoVo(perms,roleKeyList, BeanCopyUtils.copyBean(loginUser.getUser(), UserInfoVo.class));

        return ResponseResult.okResult(adminUserInfoVo);
    }

    /** 获取routers */
    @GetMapping("/getRouters")
    public ResponseResult<RoutersVo> getRouters(){

        Long userId = SecurityUtils.getUserId();
        List<Menu> menus = menuService.selectRouterMenuTreeByUserId(userId);
        return ResponseResult.okResult(new RoutersVo(menus));
    }


}
